package com.xiaoxin_project.Controller;

import com.xiaoxin_project.Util.FastDFSClient;
import com.xiaoxin_project.Util.FileUtils;
import com.xiaoxin_project.Util.IMoocJSONResult;
import com.xiaoxin_project.Util.MD5Utils;
import com.xiaoxin_project.enums.OperatorFriendRequestTypeEnum;
import com.xiaoxin_project.enums.SearchFriendsStatusEnum;
import com.xiaoxin_project.mapper.MyFriendsMapper;
import com.xiaoxin_project.pojo.ChatMsg;
import com.xiaoxin_project.pojo.Users;
import com.xiaoxin_project.pojo.bo.UsersBo;
import com.xiaoxin_project.pojo.vo.MyFriendsVo;
import com.xiaoxin_project.pojo.vo.UsersVo;
import com.xiaoxin_project.service.FriendService;
import com.xiaoxin_project.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.*;
import java.util.List;

@RestController
@RequestMapping("/user" )
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private FriendService friendService;


    @Autowired
    private FastDFSClient fastDFSClient;

    /**
     * 用户登录
     */
    @PostMapping("/registOrLogin" )
    public IMoocJSONResult registOrLogin(@RequestBody Users user) throws Exception {
        //判断用户名和密码不能为空
        if (StringUtils.isBlank(user.getUserName()) || StringUtils.isBlank(user.getPassWord())) {
            return IMoocJSONResult.errorMsg("用户名或密码不能为空" );
        }
        //System.out.println(user.getUserName());
        //判断用户名是否存在
        boolean exist = userService.queryUsernameIsExist(user.getUserName());
        //System.out.println("===="+exist+"====");
        Users userResult = null;
        //存在就登录否则注册
        if (exist) {
            //登录
            userResult = userService.queryUserForLogin(user.getUserName(), MD5Utils.getMD5Str(user.getPassWord()));
            if (userResult == null) {
                return IMoocJSONResult.errorMsg("用户名或密码不正确" );
            }
        } else {
            //注册
            user.setNickName(user.getUserName());
            user.setFaceImage(null);
            user.setFaceImageBig(null);
            user.setPassWord(MD5Utils.getMD5Str(user.getPassWord()));
            userResult = userService.saveUser(user);
        }
        UsersVo userVo = new UsersVo();
        BeanUtils.copyProperties(userResult, userVo);
        return IMoocJSONResult.ok(userVo);
    }

    /**
     * 设置头像
     */
    @PostMapping("/uploadFaceBase64" )
    public IMoocJSONResult uploadFaceBase64(@RequestBody UsersBo userBo) throws Exception {
        //获取前端传过来的base64字符串转换为文件对象再上传
        String base64Data = userBo.getFaceData();
        String userFacePath = "C:\\" + userBo.getUserId() + "userface64.png";

        FileUtils.base64ToFile(userFacePath, base64Data);
        //上传文件到fastDFS
        MultipartFile faceFile = FileUtils.fileToMultipart(userFacePath);
        String url = fastDFSClient.uploadBase64(faceFile);
        System.out.println(url);

        //获取收缩图的url
        String thum = "_80x80.";
        String[] split = url.split("\\." );
        String thumpImgUrl = split[0] + thum + split[1];

        //更新用户头像
        Users user = new Users();
        user.setId(userBo.getUserId());
        user.setFaceImageBig(url);
        user.setFaceImage(thumpImgUrl);

        Users users = userService.updateUserInfo(user);
        return IMoocJSONResult.ok(users);
    }

    /**
     * 设置昵称
     */
    @PostMapping("/setNickname" )
    public IMoocJSONResult setNickname(@RequestBody UsersBo userBo) throws Exception {
        Users users = new Users();
        users.setId(userBo.getUserId());
        users.setNickName(userBo.getNickName());
        System.out.println("+++===" + userBo.getUserId() + "**********" + userBo.getNickName() + "=======" );
        Users info = userService.updateUserInfo(users);
        return IMoocJSONResult.ok(info);
    }

    /**
     * 搜索好友
     */
    @PostMapping("/search" )
    public IMoocJSONResult searchUser(String myUserId, String friendUsername) throws Exception {
        if (myUserId.isEmpty() || StringUtils.isBlank(friendUsername)) {
            return IMoocJSONResult.errorMsg("用户不存在" );
        }
        //前置条件-1 搜索的用户不存在返回无此用户
        //前置条件-2 搜索的用户是自己返回不能添加自己
        //前置条件-3 搜索的用户已经是好友返回该用户已是好友

        Integer status = userService.precondttionSearchFriends(myUserId, friendUsername);
        if (status == SearchFriendsStatusEnum.SUCCESS.status) {
            Users users = userService.queryUserInfoByUsername(friendUsername);
            UsersVo usersVo = new UsersVo();
            BeanUtils.copyProperties(users, usersVo);
            return IMoocJSONResult.ok(usersVo);
        } else {
            String msg = SearchFriendsStatusEnum.getMsgByKey(status);
            return IMoocJSONResult.errorMsg(msg);
        }
    }

    /**
     * 发送添加好友请求
     */
    @PostMapping("/addFriendRequest" )
    public IMoocJSONResult addFriendRequest(String myUserId, String friendUsername) throws Exception {
        if (myUserId.isEmpty() || StringUtils.isBlank(friendUsername)) {
            return IMoocJSONResult.errorMsg("用户不存在" );
        }
        //前置条件-1 搜索的用户不存在返回无此用户
        //前置条件-2 搜索的用户是自己返回不能添加自己
        //前置条件-3 搜索的用户已经是好友返回该用户已是好友

        Integer status = userService.precondttionSearchFriends(myUserId, friendUsername);
        if (status == SearchFriendsStatusEnum.SUCCESS.status) {
            //发送请求
            userService.sendFriendRequest(myUserId, friendUsername);
        } else {
            String msg = SearchFriendsStatusEnum.getMsgByKey(status);
            return IMoocJSONResult.errorMsg(msg);
        }
        return IMoocJSONResult.ok();
    }

    /**
     * 查询好友请求列表
     */
    @PostMapping("/queryFriendRequest" )
    public IMoocJSONResult queryFriendRequest(String userId) {
        if (StringUtils.isBlank(userId)) {
            return IMoocJSONResult.errorMsg("" );
        }
        //查询用户接受到的好友申请列表
        return IMoocJSONResult.ok(userService.queryFriendRequestList(userId));
    }

    /**
     * 接收方通过或忽略好友请求
     */
    @PostMapping("/operFriendRequest" )
    public IMoocJSONResult operFriendRequest(String acceptUserId, String sendUserId, Integer operType) {
        if (acceptUserId == null || sendUserId == null || operType == null) {
            return IMoocJSONResult.errorMsg("");
        }
        //判断操作类型是否为空 如果操作类型没有对应的枚举值则抛出错误信息
        String msgByType = OperatorFriendRequestTypeEnum.getMsgByType(operType);
        if (StringUtils.isBlank(msgByType)) {
            return IMoocJSONResult.errorMsg("");
        }

        //忽略类型
        if (operType == OperatorFriendRequestTypeEnum.IGNORE.type) {
            //如果是忽略好友请求则直接删除好友请求记录
            userService.deleteFriendRequest(sendUserId,acceptUserId);
        }else{
            //如果通过请求，则互相增加好友记录到数据表，然后删除好友请求的数据库表记录(已成为的好友不用保留好友请求表记录)
            userService.passFriendRequest(sendUserId,acceptUserId);
        }
        //数据库查询好友列表
        List<MyFriendsVo> myFriendsVos = userService.queryMyFriends(acceptUserId);
        return IMoocJSONResult.ok(myFriendsVos);
    }

    /**
     * 查询我的好友列表
     */
    @PostMapping("/myFriends" )
    public IMoocJSONResult myFriends(String myUserId) {
        System.out.println("获取到用户id"+myUserId);
        if (StringUtils.isBlank(myUserId)) {
            return IMoocJSONResult.errorMsg("");
        }
        //查询好友列表
        List<MyFriendsVo> myFriendsVos = userService.queryMyFriends(myUserId);
        //System.out.println("tttttttttttttttttttttttttttttttttt-======"+myFriendsVos);
        return IMoocJSONResult.ok(myFriendsVos);
    }

    /**
     *  获取未读消息列表
     */
    @PostMapping("/getUnReadMsgList" )
    public IMoocJSONResult getUnReadMsgList(String acceptUserId) {
        if (StringUtils.isBlank(acceptUserId)) {
            return IMoocJSONResult.errorMsg("");
        }
        //查询列表
        List<ChatMsg> unReadMsgList = userService.getUnReadMsgList(acceptUserId);
        return IMoocJSONResult.ok(unReadMsgList);
    }

    /**
     *添加好友
     */
    /*@PostMapping("/addFriendRequest")
    public IMoocJSONResult addFriendRequest(String myUserId,String friendUsername) throws Exception {
        Users friendusers = userService.queryUserInfoByUsername(friendUsername);
        boolean flag = friendService.addFriends(myUserId, friendusers.getId());
        if (flag) {
            return IMoocJSONResult.ok("添加成功.");
        }
        return IMoocJSONResult.errorMsg("添加失败.");
    }*/
}
